package es.upm.telcoblocks.echarts.features.personalization;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import java.util.StringTokenizer;

import org.apache.log4j.Logger;
import org.echarts.servlet.sip.EChartsMachineToJava;

/**
   Implementation of the PersonalizationMachineToJava interface.
*/
public class PersonalizationMachineToJavaImpl extends EChartsMachineToJava implements PersonalizationMachineToJava{
	private static Logger logger = Logger.getLogger(PersonalizationMachineToJavaImpl.class);
	
	/**
	   Establishes communication with the rules server
	 */
	public String getData(String profile) {
		logger.info("Getting information realated to " + profile);
		String result = null;
		
		//Send the profile to the rules server 
		int port = 4444;
        String host = "localhost";
        DatagramSocket sock;
		try {
			sock = new DatagramSocket();
			byte[] info = profile.getBytes();
        	sendRequest(port,host,sock,info);
        	logger.info("Sending request " + profile);

        	//Wait for the answer and get the name of the advert
        	byte[] data = new byte[1500];
        	DatagramPacket received = new DatagramPacket(data, data.length);
        	sock.receive(received);
        	StringTokenizer respond = new StringTokenizer(new String(received.getData()), ".");
        	result= respond.nextToken();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
     * Sends a request to the rules server
     * @param port - rules server port
     * @param host - rules server host
     * @param sock - socket
     * @param info - request
     * @throws java.io.IOException
     */
    private static void sendRequest(int port, String host, DatagramSocket sock, byte[] info) throws IOException{
        InetAddress address = InetAddress.getByName(host);
        DatagramPacket peticion = new DatagramPacket(info,info.length,address,port);
        sock.send(peticion);
        logger.info("Petición enviada al servidor");
    }
}